import csv
from bs4 import BeautifulSoup
from datetime import datetime


def parse_html_to_csv(html_path, csv_path):
    with open(html_path, "r", encoding="utf-8") as f:
        html_content = f.read()

    soup = BeautifulSoup(html_content, "lxml")

    # ===== 1. 定位所有面试日期区块 =====
    date_sections = soup.select('div.interview-list-C > ul.interview-of-date')
    print(f"找到 {len(date_sections)} 个日期区块")  # 调试

    data = []
    for section in date_sections:
        # ===== 2. 提取日期 =====
        date_div = section.find('div', class_='interview-date')
        if date_div:
            date_raw = date_div.find('span', class_='first-date').get_text(strip=True)
            # 清洗日期格式（示例："01 04月 01日" → "2025-04-01"）
            try:
                day, month_part = date_raw.split('月')
                day = day.strip().split()[-1]  # 提取 "01"
                month = month_part.split('日')[0].strip()
                formatted_date = f"2025-{month.zfill(2)}-{day.zfill(2)}"  # 假设年份为2025
            except:
                formatted_date = date_raw
        else:
            formatted_date = "未知日期"

        # ===== 3. 提取面试条目 =====
        items = section.select('div.interview-list-date > div.content.item.disabled')
        print(f"日期 {formatted_date} 下找到 {len(items)} 条面试记录")  # 调试

        for item in items:
            # === 时间 ===
            time_div = item.select_one('div.time-content div:first-child')
            time = time_div.get_text(strip=True) if time_div else ""

            # === 姓名 ===
            name_span = item.select_one('span.geek-name')
            name = name_span.get_text(strip=True) if name_span else ""

            # === 岗位 === (处理换行问题)
            position_span = item.select_one('span.geek-position')
            if position_span:
                position = ' '.join(position_span.stripped_strings)
            else:
                position = ""

            # === 电话 ===
            phone_span = item.select_one('div.phone span.text')
            phone = phone_span.get_text(strip=True) if phone_span else ""

            data.append({
                "日期": formatted_date,
                "时间": time,
                "姓名": name,
                "岗位": position,
                "电话": phone
            })

    # ===== 4. 按日期排序 =====
    try:
        data.sort(key=lambda x: datetime.strptime(x["日期"], "%Y-%m-%d"))
    except:
        pass  # 如果日期格式错误保留原始顺序

    # ===== 5. 写入CSV =====
    if data:
        with open(csv_path, "w", newline="", encoding="utf-8-sig") as f:
            writer = csv.DictWriter(f, fieldnames=["日期", "时间", "姓名", "岗位", "电话"])
            writer.writeheader()
            writer.writerows(data)
        print(f"成功导出 {len(data)} 条数据到: {csv_path}")
    else:
        print("警告：未提取到任何数据！请检查HTML结构或选择器。")


# 使用示例
parse_html_to_csv("BOSS.html", "面试数据.csv")